var MyInputComponent = easyMe.import("public/javascripts/widget/myInput/myInput.js");
var selectFactory = easyMe.import("public/javascripts/widget/select/select.js");
var ordersService = easyMe.import("public/javascripts/service/ordersService.js");
var classNames = easyMe.import("public/common/classNames.js");
var cx = classNames;
var ProductComponent = React.createClass({
    componentDidMount: function() {
        var self = this;
        if(self.state.info.from === "feeTrial"){
            var data = JSON.parse(localStorage.getItem("feeTrialData"));
            self.state.data.cargoType = data.cargoType;
            self.state.data.cargoTypeName = data.cargoTypeName;
            self.state.data.cargoTypeCode = data.cargoTypeCode;
            self.state.data.currencyUnitCode = data.currencyUnitCode;
            self.state.data.currencyUnitName = data.currencyUnitName;
            self.state.data.cusWeight = data.cusWeight;
            self.state.data.cusWeightUnit = data.cusWeightUnit;
            self.state.data.cusWeightUnitName = data.cusWeightUnitName;
            self.checkServiceIds();
        }else if(self.state.info.from === "orders"){
            if(self.state.data.orderAdditionalDtos && self.state.data.orderAdditionalDtos.length > 0){
                self.state.data.orderAdditionalDtos.forEach(function(val, index){
                    self.state.data.productInfo.optionalServiceTypes.forEach(function(subVal, subIndex){
                        if(val.serviceTypeCode === subVal.serviceTypeCode){
                            subVal.checked = true;
                        }
                    });
                });
            }
            self.setState();
        }else if(self.state.info.from === "product"){
            self.state.data.cusWeightUnit = 'kg';
            self.state.data.cusWeightUnitName = '千克';
            if(self.state.data.productInfo.cargos && self.state.data.productInfo.cargos.length > 0){
                self.state.data.cargoTypeCode = self.state.data.productInfo.cargos[0].cargoTypeCode;
                self.state.data.cargoTypeName = self.state.data.productInfo.cargos[0].cargoTypeName;
            }else{
                self.state.data.cargoTypeCode = '';
                self.state.data.cargoTypeName = '';
            }
            self.checkServiceIds();
        }else if(self.state.info.from === "highVolumeOrders") {

            var errorDtoMap = self.state.info.errorDtoMap;

            if(self.state.data.orderAdditionalDtos && self.state.data.orderAdditionalDtos.length > 0){
                self.state.data.orderAdditionalDtos.forEach(function(val, index){
                    self.state.data.productInfo.optionalServiceTypes.forEach(function(subVal, subIndex){
                        if(val.serviceTypeCode === subVal.serviceTypeCode){
                            subVal.checked = true;
                        }
                    });
                });
            }
            self.setState();

            //添加后台来的错误的校验，分别放在info里面

            if(errorDtoMap) {
                if(errorDtoMap.productName ){
                    self.refs["productName"].showErrorMsg(errorDtoMap.productName.message);
                }

                if(errorDtoMap.externalNo){
                    self.refs["externalNo"].showErrorMsg(errorDtoMap.externalNo.message);
                }

                if(errorDtoMap.packageNum){
                    self.refs["packageNum"].showErrorMsg(errorDtoMap.packageNum.message);
                }
                if(errorDtoMap.cusWeight){
                    self.refs["cusWeight"].showErrorMsg(errorDtoMap.cusWeight.message);
                }

                if(errorDtoMap.cusWeightUnit){
                    self.refs["cusWeightUnit"].showErrorMsg(errorDtoMap.cusWeightUnit.message);
                }


                if(errorDtoMap.cargoType){
                    self.refs["cargoTypeName"].showErrorMsg(errorDtoMap.cargoType.message);
                }
                self.checkServiceIds();

            }

        }

        //选择产品初始化
        selectFactory({
            data: [],
            id: 'productName',
            defaultText: '请选择',
            defaultCount: 1000,
            isSearch: true,
            searchPlaceHoder: '请输入名称',
            isSaveInputVal: true,
            pagination: true,
            maxHeight: 165,
            isCreateNewSelect: true,
            onSearchValueChange: function(attachEle, q, currentPage){
                var qs = q || '';

                ordersService.productList(qs, currentPage, function(res){
                    if(res.errorCode === 0){
                        attachEle.setData(res);
                    }
                });
            },
            attrTextModel: function(name, data, item){
                self.state.data["productCode"] = item.code;
                self.state.data["productName"] = item.name;
                self.state.data["productUid"] = item.uid;
                self.state.data["productCode"] = item.code;

                if(item.cargos && item.cargos.length > 0){
                    self.state.data.cargoTypeCode = item.cargos[0].cargoTypeCode;
                    self.state.data.cargoTypeName = item.cargos[0].cargoTypeName;
                    self.state.data.cargoType = item.cargos[0].cargoTypeCode;
                }else{
                    self.state.data.cargoTypeCode = '';
                    self.state.data.cargoTypeName = '';
                    self.state.data.cargoType = '';
                }
                self.state.data["cusWeight"] = "";
                self.state.data["packageNum"] = "";
                self.state.data.productInfo = item;
                self.refs["cusWeight"].hideErrorMsg();
                self.refs["packageNum"].hideErrorMsg();

                self.refs["productName"].hideErrorMsg();
                self.setState();
                eventFlux.dispatch(['orders_address_Event'], {change: 'product', data: item});
            }
        });
        //重量单位初始化
        var cusWeightUnitEle = selectFactory({
            data: [],
            id: "cusWeightUnit",
            defaultText: '请选择',
            defaultCount: 1000,
            isSaveInputVal: true,
            isCreateNewSelect: true,
            onSearchValueChange: function(){
                ordersService.unitWeight(function(res){
                    if(res.errorCode === 0){
                        res.data.forEach(function(val){
                            val.codeName = val.name;
                            val.name = val.code;
                        });
                        cusWeightUnitEle.setData(res)
                    }
                });
            },
            attrTextModel: function(name, data, item){
                self.state.data.cusWeightUnitName = item.codeName;
                self.state.data.cusWeightUnit = item.code;
                self.checkWeight();

                self.refs["cusWeightUnit"].hideErrorMsg();

                self.setState();
            }
        });
        //货物类型初始化
        var cargoTypeNameEle = selectFactory({
            data: [],
            id: "cargoTypeName",
            defaultText: "请选择",
            defaultCount: 1000,
            isSaveInputVal: true,
            isCreateNewSelect: true,
            onSearchValueChange: function(){
                var cargoTypeNames = {};
                cargoTypeNames.data = $.extend([],self.state.data.productInfo.cargos);
                cargoTypeNames.data.forEach(function(val, index){
                    val.name = val.cargoTypeName;
                });
                cargoTypeNameEle.setData(cargoTypeNames);
            },
            attrTextModel: function(name, data, item){
                self.state.data.cargoTypeName = name;
                self.state.data.cargoTypeCode = item.cargoTypeCode;
                self.state.data.cargoType = item.cargoTypeCode;
                self.refs["cargoTypeName"].hideErrorMsg();
                self.setState();
            }
        });
    },
    receiveMsg: function(data) {
    },
    getInitialState: function () {
        return this.props ? this.props : {};
    },
    checkData:function () {

        var self = this;
        var keys = ["productName", "cargoTypeName", "packageNum"];
        if(!self.state.data.externalNo){
            keys.push("externalNo");
        }
        if(!self.state.data.cusWeightUnit){
            keys.push("cusWeightUnit");
        }
        if(!self.state.data.cusWeight){
            keys.push("cusWeight");
        }
        for(var index = 0; index < keys.length; index++) {
            this.refs[keys[index]].isOk()
        }

    },
    getData: function(callback){
        var isOk = true;
        var self = this;
        var resultData;
        var keys = ["productName", "cargoTypeName", "packageNum"];
        if(!self.state.data.externalNo){
            keys.push("externalNo");
        }
        if(!self.state.data.cusWeightUnit){
            keys.push("cusWeightUnit");
        }
        if(!self.state.data.cusWeight){
            keys.push("cusWeight");
        }
        for(var index = 0; index < keys.length; index++) {
            if(!this.refs[keys[index]].isOk()) {
                isOk = false;
            }
        }
        if($(".error-msg").length > 0){
            isOk = false;
        }
        if(isOk){
            var datas = self.state.data,
                subData = $.extend([],self.state.data.productInfo.optionalServiceTypes),
                dataArr = [];
            subData.forEach(function(val, index){
                if(val.checked){
                    if(val.orderNo){
                        dataArr.push({
                            serviceTypeCode: val.serviceTypeCode,
                            serviceTypeName: val.serviceTypeName,
                            orderNo: val.orderNo
                        });
                    }else {
                        dataArr.push({
                            serviceTypeCode: val.serviceTypeCode,
                            serviceTypeName: val.serviceTypeName
                        });
                    }
                }
            });

            resultData = {
                productId: datas.productInfo.id,
                productUid: datas.productInfo.uid,
                productName: datas.productInfo.name,
                productCode: datas.productInfo.code,
                externalNo: datas.externalNo,
                cargoType: datas.cargoTypeCode || datas.cargoType,
                cargoTypeCode: datas.cargoTypeCode || datas.cargoType,
                cargoTypeName: datas.cargoTypeName,
                cusWeight: datas.cusWeight,
                cusWeightUnit: datas.cusWeightUnit,
                cusWeightUnitName: datas.cusWeightUnitName,
                packageNum: datas.packageNum,
                orderAdditionalDtos: dataArr,
                productCode:datas.productCode
            };
        }else{
            resultData = false;
        }
        callback(resultData);
    },
    checkServiceIds: function(){
        var self = this;

        if(self.state.info.serviceids && self.state.info.serviceids.length > 0){
            self.state.info.serviceids.forEach(function(val, index){
                self.state.data.productInfo.optionalServiceTypes.forEach(function(subVal, subIndex){
                    if(val.serviceTypeCode === subVal.serviceTypeCode){
                        subVal.checked = true;
                    }
                });
            });
        }
        self.setState();
    },
    getServiceData: function(){
        //获取服务
        var productUid = this.state.data.productInfo.uid;
        var self = this;
        var serviceConfig = {
            urlParams: {
                'uid': productUid
            }
        };
        ordersService.hasReceived(serviceConfig,function(res){
            if(res.errorCode === 0){
                if(res.data.serviceReceiveInfo && res.data.serviceReceiveInfo.length === 0){
                    self.setState();
                }else{
                    var receivedService = $.extend([],res.data.serviceReceiveInfo);
                    var optionalServiceTypes = $.extend([], self.state.data.productInfo.optionalServiceTypes);
                    receivedService.forEach(function(val, index){
                        if(val.serviceReceive){
                            optionalServiceTypes.forEach(function(subVal, subIndex){
                                if(subVal.serviceTypeCode === val.serviceTypeCode){
                                    subVal.checked = true;
                                }else{
                                    subVal.checked = false;
                                }
                            });
                        }
                    });
                    self.state.data.productInfo.optionalServiceTypes = optionalServiceTypes;
                    self.setState();
                }
            }
        });
    },
    autoGenerateNo: function(e){
        var self = this;
        //自动生成单号
        if(e.target.checked){
            ordersService.cusOrderNo('',function(res){
                if(res.errorCode === 0){
                    self.state.data["externalNo"] = res.data;
                    self.setState();
                }
            });
        }else{
            self.state.data["externalNo"] = "";
            self.setState();
        }
        self.refs["externalNo"].hideErrorMsg();
    },
    selectItemFn: function(item){
        if(item.checked){
            this.state.data.productInfo.optionalServiceTypes.forEach(function(val, index){
                if(val.serviceTypeCode === item.serviceTypeCode){
                    val.checked = false;
                }
            })
        }else{
            this.state.data.productInfo.optionalServiceTypes.forEach(function(val, index){
                if(val.serviceTypeCode === item.serviceTypeCode){
                    val.checked = true;
                }
            })
        }
        var datas = $.extend([],this.state.data.productInfo.optionalServiceTypes),
            dataArr = [];
        datas.forEach(function(val, index){
            if(val.checked){
                if(val.orderNo){
                    dataArr.push({
                        serviceTypeCode: val.serviceTypeCode,
                        serviceTypeName: val.serviceTypeName,
                        orderNo: val.orderNo
                    });
                }else {
                    dataArr.push({
                        serviceTypeCode: val.serviceTypeCode,
                        serviceTypeName: val.serviceTypeName
                    });
                }
            }
        });
        eventFlux.dispatch(['orders_address_Event'], {'change': 'service', 'data': dataArr});
        this.setState();
    },
    checkWeight: function(){

            if(!$("#cusWeight").next("span").hasClass("error-msg") || $("#cusWeight").next("span").hasClass("error-msg") && ($("#cusWeight").next("span").html().indexOf("重量不在范围内") !== -1)){
                var uid = this.state.data.productInfo.uid,
                    weight = this.state.data.cusWeight || 0,
                    unit = this.state.data.cusWeightUnit;
                var self = this;
                ordersService.checkweight(uid, weight, unit, function(res){
                    if(res.errorCode === 0){
                        if(res.data){
                            self.refs["cusWeight"].hideErrorMsg();
                        }else{
                            self.refs["cusWeight"].showErrorMsg(res.msg);
                        }
                    }
                });
            }


    },
    checkExternalNo: function(){
        var self = this;
        var val = self.state.data.externalNo;
        var id = self.state.data.id || 0;
        ordersService.cusOrderNoExist(val, id, function(res){
            if(res.errorCode === 0){
                if(res.data !== null){
                    self.refs["externalNo"].showErrorMsg("客户单号已存在");
                    return false;
                }
            }
        });
    },
    handleClick: function() {
        //eventFlux.dispatch(['address', 'index_init_Event'], {username: "xiaop"});
        //eventFlux.broadcast({username: "xiaop"});
    },
    render:function() {
        var data = this.state.data;
        var info = this.state.info;
        var component = this;
        return ~product;
    }
});
module.exports = ProductComponent;

